package com.touchealth.test.http;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhangyanqiang
 * @date 2020/12/25
 **/
public class PhoneNumber {
    public static void main(String[] args) {
        ExcelReader reader = ExcelUtil.getReader(FileUtil.file("/Users/zhangyanqiang/Documents/workspace/self/demo/src/main/java/com/touchealth/test/http/template.xlsx"));

        List<Map<String, Object>> readAll = reader.readAll();
        AtomicInteger num = new AtomicInteger();
        ExecutorService cachedThreadPool  = Executors.newFixedThreadPool(30);
        ExcelWriter writer = ExcelUtil.getWriter("/Users/zhangyanqiang/Documents/workspace/self/demo/src/main/java/com/touchealth/test/http/writeTest.xlsx");
        writer.passCurrentRow();
        List<List<String>> rows = new Vector<>(340000);

        readAll.forEach(r ->{
            cachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    if(r.get("号码")!=null){
                        String tel = r.get("号码").toString();
                        HashMap<String, Object> paramMap = new HashMap<>();
                        paramMap.put("tel", tel);
                        String result3= HttpUtil.get("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm", paramMap);
                        JSONObject obj = parseTBStr(result3);
                        String area = obj.getStr("carrier");
                        if (area.indexOf("浙江")>-1){
                            num.addAndGet(1);
                            System.out.println(num);
                            System.out.println("手机号 "+tel+" 区域 "+ area);
                        }
                        List<String> row1 = CollUtil.newArrayList(tel, area);
                        rows.add(row1);
                    }
                }
            });

        });
        writer.write(rows);
        writer.close();
    }

    public static JSONObject parseTBStr(String str) {
        JSONObject obj = new JSONObject();
        if (str.contains("\t")) str = str.replace("\t", "");
        str = str.substring(str.indexOf("{") + 1, str.length() - 1);
        String[] items = str.split(",");
        for (int i = 0; i < items.length; i++) {
            String[] split = items[i].split(":");
            obj.put(split[0].trim(), split[1].substring(1, split[1].length() - 1).trim());
        }
        return obj;
    }
}
